<?php

namespace backend\logic;

use think\Db;
use external\SFTools;

class UserLogic {
    /**
     * 根据手机号码新增一条用户资料（如果用户已存在则直接返回用户资料）
     * @param   string $phone 电话号码
     * @return  array          数组对象数据
     */
    public function saveUserFind($phone) {
        if (!preg_match(PREG_MATCH_PHONE, $phone)) {
            return SFTools::err("3311");
        }
        $user = new \backend\model\User;
        $field = 'user_uuid,accout_state';
        $userFind = $user::field($field)->where('login_account', $phone)->find();
        if (empty($userFind)) {
            $nickname = substr($phone, 0, 3) . "*****" . substr($phone, -3);
            $pwd = md5(substr($phone, -6));
            $user->nickname = $nickname;
            $user->login_account = $phone;
            $user->login_pwd = $pwd;
            $user->accout_state = 1;
            $user->save();
            $userFind['user_uuid'] = $user->user_uuid;
            $userFind['accout_state'] = $user->accout_state;
        }
        return $userFind;
    }

    /**
     * 获取用户信息
     * @param   string $user_uuid 用户唯一标识
     * @return  array             数组对象数据
     */
    public function getUserFindToTicket($user_uuid) {
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        $cookie_key = SFTools::getCookieKey();
        $cache_key_str = SERVICE_APP_ID . $user_uuid;
        $cache_key = md5($cache_key_str);
        setcookie($cookie_key, $cache_key, 0, '/');
        $userFind['user_uuid'] = $user_uuid;
        return $userFind;
    }

    /**
     * 根据用户唯一获取用户信息
     * @param   string $user_uuid 用户唯一标识
     * @return  array             数组对象数据
     */
    public function getUserFindBuyUserUUID($user_uuid) {
        if (empty($user_uuid)) {
            return SFTools::err("3300");
        }
        $user = new \backend\model\User;
        $field = '*';
        return $user::field($field)->where('user_uuid', $user_uuid)->find();
    }
}